
// 是否已点击了链接测试
let isConnectClick = false
// 是否已点击了开启
let isLaunchClick = false



/**
 * @description: 获取插件统计数据
 * @return {*}
 */
async function getPuginStatisticalData(){
    await sendMessage({type: 'getPuginStatisticalData'}, (response) => {
        const {total_order_full, total_goods_full, total_order_increment, total_goods_increment, today_order_full, today_goods_full, today_order_increment, today_goods_increment} = response
        $("#total_order_full").text(total_order_full);
        $("#total_goods_full").text(total_goods_full);
        $("#total_order_increment").text(total_order_increment);
        $("#total_goods_increment").text(total_goods_increment);
        $("#today_order_full").text(today_order_full);
        $("#today_goods_full").text(today_goods_full);
        $("#today_order_increment").text(today_order_increment);
        $("#today_goods_increment").text(today_goods_increment);
    })
}


/**
 * @description: 获取插件配置信息
 * @return {*}
 */
async function getPluginInfo (){
    await sendMessage({type: 'getPluginInfo'}, (response) => {
        const {channel, retail_shop_id, external_shop_id, shop_name, external_shop_account, app_key, app_secret} = response
        $("#channelSelect").val(channel);
        $("#retailShopIdInput").val(retail_shop_id);
        $("#externalShopIdInput").val(external_shop_id);
        $("#shopNameInput").val(shop_name);
        $("#externalShopAccountInput").val(external_shop_account);
        $("#appKeyInput").val(app_key);
        $("#appSecretInput").val(app_secret);
    })
}

/**
 * @description: 获取插件状态
 * @return {*}
 */
async function getPluginStatus (){
    await sendMessage({type: 'getPluginStatus'}, (response) => {
        const {shop_name, shop_logo_path, isLooping, loopStatus, isConnected, connectStatus, connectErrMsg, loopingMsg, pluginStartTime, pluginEndTime, loopingStartTime} = response
        if(isLooping){
            $("#main").css('display', 'none')
            $("#looping").css('display', 'block')
            $("#store_name").text(shop_name)
            $("#store_logo").attr("src", `../asset/img/${shop_logo_path}.png`)
            $("#store_status").text(loopingMsg);
            $("#looping_start_time").text(`数据统计时间：${loopingStartTime} 至今`)
            $("#start_time").text('');
            $("#error_time").text('');
            if(loopStatus){
                if($("#store_status").hasClass('store_status_err')){
                    $("#store_status").removeClass('store_status_err')
                }
                $("#start_time").text(`开始运行于 ${pluginStartTime}`);
            }else{
                if(!$("#store_status").hasClass('store_status_err')){
                    $("#store_status").addClass('store_status_err')
                }
                $("#error_time").text(`异常停止时间：${pluginEndTime}`);
            }
        }else if(isConnected){
            $("#main").css('display', 'block')
            $("#looping").css('display', 'none')
            $("#connect").text('重新连接');
            $("#success").text('');
            $("#error").text('');
            if(connectStatus){
                $("#success").text('连接成功！！！');
            }else{
                $("#error").text(connectErrMsg);
            }
        }else{
            $("#main").css('display', 'block')
            $("#looping").css('display', 'none')
            $("#connect").text('连接测试');
            $("#success").text('');
            $("#error").text('');
        }
    })
}

/**
 * @description: 封装发送方法
 * @param {*} message  需要发生的消息
 * @param {*} callback  回调
 * @return {*}
 */
function sendMessage(message, callback){
    return new Promise((resolve, reject)=>{
        try {
            chrome.tabs.query({currentWindow: true, active: true}, tabs => {
                chrome.tabs.sendMessage(tabs[0].id, message, (response) => {
                    callback && callback(response)
                    resolve(response)
                });
            });
        } catch (error) {
            reject(error)
        }
    })
}

/**
 * @description: 表单校验
 * @return {*}
 */
function validateForm (){
    let flag = true;
    let errArr = $(".err");
    for (let i = 0; i < errArr.length; i++) {
        errArr[i].innerHTML = "";
    }
    const channel = $('#channelSelect').val();
    const retail_shop_id = $('#retailShopIdInput').val().trim();
    const external_shop_id = $('#externalShopIdInput').val().trim();
    const shop_name = $('#shopNameInput').val().trim();
    const external_shop_account = $('#externalShopAccountInput').val().trim();
    const app_key = $('#appKeyInput').val().trim();
    const app_secret = $('#appSecretInput').val().trim();
    if (!channel) {
        errArr[0].innerHTML = "请选择店铺类型";
        flag = false;
    }
    if (!retail_shop_id) {
        errArr[1].innerHTML = "请输入客易达店铺ID";
        flag = false;
    }
    if (!external_shop_id) {
        errArr[2].innerHTML = "请输入店铺ID";
        flag = false;
    }
    if (!shop_name) {
        errArr[3].innerHTML = "请输入店铺名称";
        flag = false;
    }
    if (!external_shop_account) {
        errArr[4].innerHTML = "请输入淘宝账号名";
        flag = false;
    }
    if (!app_key) {
        errArr[5].innerHTML = "请输入App Key";
        flag = false;
    }
    if (!app_secret) {
        errArr[6].innerHTML = "请输入App Secret";
        flag = false;
    }
    if(flag){
        return {channel, retail_shop_id, external_shop_id, shop_name, external_shop_account, app_key, app_secret}
    }else{
        return false
    }
}

/**
 * @description: 连接测试按钮点击事件
 * @return {*}
 */
function addConnectListener(){
    $('#connect').click(async () => {
        $("#error").text('');
        $("#success").text('');
        const data = validateForm()
        if(data && !isConnectClick){
            isConnectClick = true
            await sendMessage({type: 'connect', data}, (response) => {
                getPluginStatus()
                getPluginInfo()
                isConnectClick = false
            })
        }
    })
}

/**
 * @description: 启动按钮点击事件
 * @return {*}
 */
function addLaunchListener(){
    $('#launch').click(async () => {
        $("#error").text('');
        $("#success").text('');
        const data = validateForm()
        if(data && !isLaunchClick){
            isLaunchClick = true
            await sendMessage({type: 'launch_', data}, (response) => {
                getPluginStatus()
                getPluginInfo()
                getPuginStatisticalData()
                isLaunchClick = false
            })
        }
    })
}


/**
 * @description: 停止按钮点击事件
 * @return {*}
 */
function addStopListener(){
    $('#stop').click(async () => {
        await sendMessage({type: 'stop_'}, (response) => {
            getPluginStatus()
            getPluginInfo()
        })
    })
}


/**
 * @description: 监听表单change事件
 * @return {*}
 */
function addFormChangeListener(){
    $("select,input[type=text]").on("change input", async res => {
        const data = {}
        const currentTarget = $(res.currentTarget)
        const value = currentTarget.val().trim()
        const name = currentTarget.prop('name')
        data[name] = value
        await sendMessage({type: 'change', data})
    })
}


document.addEventListener('DOMContentLoaded', async () => {
    await getPluginStatus()
    await getPluginInfo()
    await getPuginStatisticalData()
    addConnectListener()
    addLaunchListener()
    addStopListener()
    addFormChangeListener()
})

